package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.mapper.BehaviorMapper;
import com.heima.behavior.service.BehaviorService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadDto;
import com.heima.model.behavior.pojos.BeBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.utils.common.APUserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BehaviorServiceImpl implements BehaviorService {
    @Autowired
    private BehaviorMapper behaviorMapper;

    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {
        //文章
        if (dto.getType() == 0) {
            BeBehavior beBehavior = new BeBehavior();
            beBehavior.setUserId(APUserThreadLocalUtil.getUser());
            beBehavior.setArticleId(dto.getArticleId());
            beBehavior.setIsLike(Integer.valueOf(dto.getOperation()));
            behaviorMapper.update(beBehavior, new LambdaQueryWrapper<BeBehavior>()
                    .eq(BeBehavior::getArticleId, beBehavior.getArticleId())
                    .eq(BeBehavior::getUserId, beBehavior.getUserId()));
        }
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult readBehavior(ReadDto dto) {
        BeBehavior upBeBehavior = new BeBehavior();
        upBeBehavior.setUserId(APUserThreadLocalUtil.getUser());
        upBeBehavior.setArticleId(dto.getArticleId());
        BeBehavior beBehavior = behaviorMapper.selectOne(new LambdaQueryWrapper<BeBehavior>()
                .eq(BeBehavior::getArticleId, upBeBehavior.getArticleId())
                .eq(BeBehavior::getUserId, upBeBehavior.getUserId()));
        if (beBehavior != null) {
            upBeBehavior.setCount(beBehavior.getCount() + 1);
        } else {
            upBeBehavior.setCount(1);
        }
        behaviorMapper.insert(upBeBehavior);
        return ResponseResult.okResult(null);
    }

    @Override
    public ResponseResult unLikesBehavior(LikesBehaviorDto dto) {
        BeBehavior beBehavior = new BeBehavior();
        beBehavior.setUserId(APUserThreadLocalUtil.getUser());
        beBehavior.setArticleId(dto.getArticleId());
        behaviorMapper.update(beBehavior, new LambdaQueryWrapper<BeBehavior>()
                .eq(BeBehavior::getArticleId, beBehavior.getArticleId())
                .eq(BeBehavior::getUserId, beBehavior.getUserId()));
        return ResponseResult.okResult(null);
    }
}
